Vue Js Get Class of Clicked Element:In Vue.js, you can get the class of a clicked element by using the $event object and the target property.
When an element is clicked, the browser creates an event object that contains information about the event, including the target element. In Vue.js, you can access this event object using the $event parameter in the method that is called when the element is clicked.
To get the class of the clicked element, you can use the target property of the $event object, and then access the classList property of the target element to get an array of all the classes on the element.
How can I get the class of a clicked element in Vue js?
To get the class of the clicked element. When a user clicks on an element, the getClass
method is called with the event
object. The event.target
property gives you the clicked element. You can then access the classList
property of the element to get an array-like object of all the classes on that element.
To display the classes in an alert box, you can use the alert
function and pass in the classes
variable.
Vue Js Get Class of Clicked Element Example
<div id="app">
<div @click="getClass($event)" class='class1'>Click me</div>
<button @click="getClass($event)" class="class2">Button 1</button>
<button @click="getClass($event)" class="class3">Button 2</button>
<button @click="getClass($event)" class="class4">Button 3</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
methods: {
getClass(event) {
const clickedElement = event.target;
const classes = clickedElement.classList;
alert(classes); // logs the classes of the clicked element
}
}
});
</script>